/*
 * Copyright (C) 2011 Nicola Bonzanni
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.vu.few.ibivu.jlemon;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import nl.vu.few.ibivu.jlemon.concepts.AddArcHandler;
import nl.vu.few.ibivu.jlemon.concepts.Arc;
import nl.vu.few.ibivu.jlemon.concepts.ClearHandler;
import nl.vu.few.ibivu.jlemon.concepts.Graph;
import nl.vu.few.ibivu.jlemon.concepts.EraseArcHandler;

public class ArcMap<A extends Arc & Comparable<A>, V> extends
		AbstractVectorMap<A, V> implements AddArcHandler<A>,
		EraseArcHandler<A>, ClearHandler, Serializable {

	private static final long serialVersionUID = 1L;
	Graph<?, A> graph;
	
	public ArcMap(ArcMap<A,V> arcMap) {
		super(arcMap.keySet(), arcMap.graph.maxArcId() + 1);
		this.graph = arcMap.graph;
		putAll(arcMap);
	}

	public ArcMap(Graph<?, A> graph) {
		super(new AsArcSet<A>(graph), graph.maxArcId() + 1);
		this.graph = graph;
	}
	
	public ArcMap(Graph<?, A> graph, V initValue) {
		super(new AsArcSet<A>(graph), graph.maxArcId() + 1, initValue);
		this.graph = graph;
	}
	
	public Graph<?, A> getGraph() {
		return graph;
	}

	@Override
	protected int getId(Object key) {
		if (graph.getArcClass().isInstance(key)) {
			return graph.id(graph.getArcClass().cast(key));
		}
		return -1;
	}

	@Override
	protected A getItem(int id) {
		return graph.arcFromId(id);
	}

	@Override
	public void onAddArc(A... arc) {
		adjustInternalContainer();
	}

	@Override
	public void onClear() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onEraseArc(A... arc) {
		for (int i = 0; i < arc.length; i++) {
			put(arc[i], null);
		}
	}
	
	/**
	 * Custom deserialization is needed.
	 */
	@SuppressWarnings("unchecked") // explain!
	private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
		stream.defaultReadObject();
		// manually deserialize and init superclass
		ArcMap<A,V>.InternalState state = (ArcMap<A,V>.InternalState) stream.readObject();
		init(state);
	}

	/**
	 * Custom serialization is needed.
	 */
	private void writeObject(ObjectOutputStream stream) throws IOException {
		stream.defaultWriteObject();
		// manually serialize superclass
		stream.writeObject(getInternalState());
	}
}
